package com.lightsaber.trade.as.service.reta;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.lightsaber.trade.as.dao.reta.OrderTemplateDao;
import com.lightsaber.trade.as.entity.reta.OrderTemplate;
import com.lightsaber.trade.as.entity.reta.OrderTemplateItem;
import com.lightsaber.trade.core.common.util.CurrentUser;
import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.core.entity.AuditedObject;
import com.lightsaber.trade.core.entity.BaseEntity;
import com.lightsaber.trade.core.service.BaseServiceImpl;

@Service
@Transactional
public class OrderTemplateManager extends BaseServiceImpl<OrderTemplate, String> {
    @Autowired
    private OrderTemplateDao orderTemplateDao;

    @Override
    protected BaseDao<OrderTemplate, String> getDao() {
        return orderTemplateDao;
    }

    public void findPage(OrderTemplate orderTemplate, Page<OrderTemplate> page) {
        orderTemplateDao.findPage(orderTemplate, page);
    }

    public OrderTemplate saveOrderTemplate(OrderTemplate orderTemplate) {

        if (StringUtils.isBlank(orderTemplate.getId())) {

            orderTemplate.setOrganization(CurrentUser.getOrg());

            this.save(orderTemplate);

            return orderTemplate;
        } else {

            OrderTemplate old = this.get(orderTemplate.getId());

            BeanUtils.copyProperties(old, old, new String[] { BaseEntity.ID, BaseEntity.VERSION,
                    AuditedObject.CREATED_BY, AuditedObject.CREATED_DATE, "totalPrice",
                    "organization" });

            this.save(old);
            return old;
        }
    }

    public void onItemChanged(String orderTemplateId) {
        OrderTemplate orderTemplate = this.get(orderTemplateId);

        Double totalPrice = Double.valueOf(0d);
        for (OrderTemplateItem orderTemplateItem : orderTemplate.getOrderTemplateItemList()) {
            totalPrice += (orderTemplateItem.getNumber() * orderTemplateItem.getPrice());
        }

        orderTemplate.setTotalPrice(totalPrice);
        orderTemplateDao.save(orderTemplate);

    }

}
